﻿(function () {
    ProductSkuClass = {};
    var islock = false;//防止同时提交两次数据
    ProductSkuClass.Instance = {
        Init: function () {
            //layui资源加载
            layui.use('form', function () {
                var form = layui.form;
                form.render();
                //自定义验证规则
                form.verify({
                    //验证大于0的规则
                    greaterThanZero: function (value, item) {
                        var r = parseFloat(value);
                        if (r <= 0)
                            return "必须大于0";
                    },
                    //验证金额
                    isMoney: function (value, item) {//这条规则0也会通过，不知道咋改、
                        var pattern = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/;
                        if (!pattern.test(value))
                            return '金额格式错误,必须大于0并且保留两位小数';
                    },
                });

                //验证提交
                form.on('submit(add)', ProductSkuClass.Instance.Submit);
                //layui的ridao事件监听
                form.on('radio(skuRadio)', ProductSkuClass.Instance.ChangeSkuType);

            });
            //加载多规格数据
            ProductSkuClass.Instance.CreatePropetyHtml();
            $(document).on('click', '#btnAddPropetyName', this.AddPropety);
            $(document).on('click', '.btn_add_value', this.AddPropetyValue);
            $(document).on('click', '.Span_PropetyValue', this.DelPropetyValue);
            $(document).on('click', '.Span_PropetyName', this.DelPropety);
            $(document).on('click', '.btnBack', this.Back);
        },
        //返回
        Back: function () {
            layer.confirm('数据不会保存,确认后返回列表页?', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                window.location.href = "/Product/List";
            }, function () {

            });
        },
        AddPropetyValue: function () {
            var propetyId = $(this).attr("PropetyId");
            var propetyValue = $("#newValue_" + propetyId).val();
            if (propetyValue == "") {
                layer.alert("请输入新规格值");
                return false;
            }
            if (islock)
                return false;
            islock = true;
            layer.confirm('追加规格值会自动匹配出新商品单元', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                var model = {};
                model.SallPropetyId = propetyId;
                model.PropetyValue = $.trim(propetyValue);
                model.ProductId = ToolManager.Common.UrlParms("id");
                var index = layer.load(1);
                RequestManager.Ajax.Post("/Product/AddPropetyValue", model, true, function (data) {
                    layer.closeAll();
                    islock = false;
                    if (data.IsSuccess) {
                        ProductSkuClass.Instance.CreatePropetyHtml();
                        $("#newValue_" + propetyId).val("");
                    } else {
                        layer.alert(data.Message);
                    }
                })
            }, function () {
                islock = false;
            });
        },
        DelPropetyValue: function () {
            //判断是否当前规格只剩一个属性值了。
            if ($(this).parent().find('.Span_PropetyValue').length == 1) {
                layer.alert("必须保留1个规格值,如要删除,请删除该规格");
                return false;
            }
            if (islock)
                return false;
            islock = true;
            var sallPropetyId = $(this).attr("parrentId");
            var id = $(this).attr("vid");
            var propetyValue = $.trim($(this).attr("PropetyValue"));
            layer.confirm('删除该规格值相关商品单元也删除,要执行么?', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                var model = {};
                model.SallPropetyId = sallPropetyId;
                model.Id = id;
                model.PropetyValue = propetyValue;
                model.ProductId = ToolManager.Common.UrlParms("id");
                var index = layer.load(1);
                RequestManager.Ajax.Post("/Product/DelPropetyValue", model, true, function (data) {
                    layer.closeAll();
                    islock = false;
                    if (data.IsSuccess) {
                        ProductSkuClass.Instance.CreatePropetyHtml();
                    } else {
                        layer.alert(data.Message);
                    }
                })
            }, function () {
                islock = false;
            });
        },
        DelPropety: function () {
            var id = $(this).attr("vid");
            if (islock)
                return false;
            islock = true;
            layer.confirm('删除该规格所有商品单元将发生改变,要执行么?', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                $.get("/Product/DelPropety?id=" + id + "&productId=" + ToolManager.Common.UrlParms("id") + "&r=" + new Date().getTime(), function (data) {
                    layer.closeAll();
                    islock = false;
                    if (data.IsSuccess) {
                        ProductSkuClass.Instance.CreatePropetyHtml();
                    } else {
                        layer.alert(data.Message);
                    }
                })
            }, function () {
                islock = false;
            });
        },
        AddPropety: function () {
            if (islock)
                return false;
            islock = true;
            if ($("#skuList").find(".PropetyName").length >= 3) {
                layer.alert("最多支持3类规格");
                islock = false;
                return false;
            }
            if ($.trim($("#PropetyName").val()) == "" || $.trim($("#PropetyValue").val()) == "") {
                layer.alert("规格名称或规格值不能为空");
                islock = false;
                return false;
            }
            //如果添加进行提示数据要重新填写
            layer.confirm('更改规格将要重新设置价格,库存数据,继续执行么?', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                var model = {};
                model.PropetyName = $.trim($("#PropetyName").val());
                model.PropetyValue = $.trim($("#PropetyValue").val());
                model.ProductId = ToolManager.Common.UrlParms("id");
                var index = layer.load(1);
                RequestManager.Ajax.Post("/Product/AddPropety", model, true, function (data) {
                    layer.closeAll();
                    islock = false;
                    if (data.IsSuccess) {
                        ProductSkuClass.Instance.CreatePropetyHtml();
                        $("#PropetyName").val("");
                        $("#PropetyValue").val("");
                    } else {
                        layer.alert(data.Message);
                    }
                })
            }, function () {
                islock = false;
            });

        },
        CreatePropetyHtml: function () {
            var index = layer.load(1);
            $.get("/Product/GetMoreSkuManager?id=" + ToolManager.Common.UrlParms("id") + "&r=" + new Date().getTime(), function (data) {
                layer.close(index);
                if (data.IsSuccess) {
                    //加载标签
                    ProductSkuClass.Instance.CreatePropetySpanHtml(data.Data);
                    //加载表格数据
                    ProductSkuClass.Instance.CreatePropetyTableHtml(data.Data);
                } else {
                    layer.alert(data.Message);
                }
            })
        },
        //动态加载规格标签
        CreatePropetySpanHtml: function (data) {
            var arr = [];
            if (data.Product_Sall_PropetyModelList.length > 0) {
                for (var i = 0; i < data.Product_Sall_PropetyModelList.length; i++) {
                    arr.push('<div class="layui-form-item">');
                    arr.push('<button vid="' + data.Product_Sall_PropetyModelList[i].Id + '" class="layui-btn Span_PropetyName">');
                    arr.push('' + data.Product_Sall_PropetyModelList[i].PropetyName + '<i class="layui-icon">&#x1007;</i>');
                    arr.push('</button>');
                    arr.push('</div>');

                    arr.push('<div class="layui-form-item">');
                    for (var j = 0; j < data.Product_Sall_PropetyModelList[i].Product_Sall_Propety_ValueList.length; j++) {
                        arr.push('<button PropetyValue="' + data.Product_Sall_PropetyModelList[i].Product_Sall_Propety_ValueList[j].PropetyValue + '" vid="' + data.Product_Sall_PropetyModelList[i].Product_Sall_Propety_ValueList[j].Id + '" parrentId="' + data.Product_Sall_PropetyModelList[i].Id + '" class="layui-btn layui-btn-primary Span_PropetyValue">' + data.Product_Sall_PropetyModelList[i].Product_Sall_Propety_ValueList[j].PropetyValue + '<i class="layui-icon">&#x1007;</i></button>');
                    }
                    arr.push('<input type="text" id="newValue_' + data.Product_Sall_PropetyModelList[i].Id + '" class="SkuValueInput" placeholder="新规格值">');
                    arr.push('<button PropetyId="' + data.Product_Sall_PropetyModelList[i].Id + '" class="layui-btn layui-btn-radius layui-btn-primary layui-btn-sm btn_add_value">添加</button>');

                    arr.push(' </div>');
                    arr.push('<hr />');
                }
            }
            $("#skuList").html(arr.join(''));
        },
        CreatePropetyTableHtml: function (data) {
            var arr = [];
            if (data.Product_Sall_PropetyModelList.length > 0) {
                arr.push('<thead><tr>');
                //--拼表头
                var propetyValueArr = [];
                for (var i = 0; i < data.Product_Sall_PropetyModelList.length; i++) {
                    arr.push('<th>' + data.Product_Sall_PropetyModelList[i].PropetyName + '</th>');
                    propetyValueArr.push(data.Product_Sall_PropetyModelList[i].Product_Sall_Propety_ValueList);
                    //将每个属性的属性值集合取出，扔进数组
                }
                arr.push('<th>销售价</th>');
                arr.push('<th>库存</th>');
                arr.push('<th>商品编码</th>');
                arr.push('<th>商品重量(kg)</th>');
                arr.push('</tr></thead>');
                arr.push('<tbody id="table_body">');
                //--拼表体
                var _cc = 0;
                var _price = ""; var _stockNum = ""; var _skucode = ""; var _weight="";
                for (var i = 0; i < propetyValueArr[0].length; i++) {
                    if (propetyValueArr[1] != undefined) {
                        for (var j = 0; j < propetyValueArr[1].length; j++) {
                            if (propetyValueArr[2] != undefined) {
                                for (var z = 0; z < propetyValueArr[2].length; z++) {
                                    var _PropetyCombineId = propetyValueArr[0][i].Id + '-' + propetyValueArr[1][j].Id + '-' + propetyValueArr[2][z].Id;
                                    //计算当前合并属性值ID是否存在已经设置的模型
                                    var _model = ProductSkuClass.Instance.GetBindSkuModel(data.MoreSkuModelList, _PropetyCombineId);
                                    if (_model != null) {
                                        _price = _model.SallPrice;
                                        _stockNum = _model.StockNum;
                                        _skucode = _model.SkuCode;
                                        _weight = _model.Weight;
                                    }
                                    arr.push('<tr ProppetyCombineName="' + propetyValueArr[0][i].PropetyValue + '+' + propetyValueArr[1][j].PropetyValue + '+' + propetyValueArr[2][z].PropetyValue + '" PropetyCombineId="' + _PropetyCombineId+ '">');
                                    //合并单元格，外层合并行数是2数组长度*3数组长度
                                    var _rowsCount1 = propetyValueArr[1].length * propetyValueArr[2].length;
                                    if (_cc % _rowsCount1 == 0)
                                        arr.push('<td rowspan="' + _rowsCount1 + '">' + propetyValueArr[0][i].PropetyValue + '</td>');
                                    //中层合并行数是3数组长度
                                    var _rowsCount2 = propetyValueArr[2].length;
                                    if (_cc % _rowsCount2 == 0)
                                        arr.push('<td rowspan="' + _rowsCount2 + '">' + propetyValueArr[1][j].PropetyValue + '</td>');
                                    arr.push('<td>' + propetyValueArr[2][z].PropetyValue + '</td>');
                                    arr.push('<td><input type="text" class="SkuValueInput2 batch_sallPrice" placeholder="销售价" value="'+_price+'" lay-verify="required|isMoney|greaterThanZero"></td>');
                                    arr.push('<td><input type="text" lay-verify="required|number"  class="SkuValueInput2 batch_stockNum" value="'+_stockNum+'" placeholder="库存"></td>');
                                    arr.push('<td><input type="text" value="' + _skucode + '" class="SkuValueInput2 batch_skuCode" placeholder="商品编码,非必填"></td>');
                                    arr.push('<td><input lay-verify="required" type="text" value="' + _weight + '" class="SkuValueInput2 batch_weight" placeholder="商品重量(kg)"></td>');
                                    arr.push('</tr>');
                                    _price = ""; _stockNum = ""; _skucode = ""; _weight = "";
                                    _cc++;
                                }
                            } else {
                                var _PropetyCombineId = propetyValueArr[0][i].Id + '-' + propetyValueArr[1][j].Id;
                                //计算当前合并属性值ID是否存在已经设置的模型
                                var _model = ProductSkuClass.Instance.GetBindSkuModel(data.MoreSkuModelList, _PropetyCombineId);
                                if (_model != null) {
                                    _price = _model.SallPrice;
                                    _stockNum = _model.StockNum;
                                    _skucode = _model.SkuCode;
                                    _weight = _model.Weight;
                                }
                                arr.push('<tr ProppetyCombineName="' + propetyValueArr[0][i].PropetyValue + '+' + propetyValueArr[1][j].PropetyValue + '" PropetyCombineId="' + _PropetyCombineId + '">');
                                //合并单元格数量
                                var _cellCount = propetyValueArr[1].length;
                                if (_cc % _cellCount == 0)
                                    arr.push('<td rowspan="' + _cellCount + '">' + propetyValueArr[0][i].PropetyValue + '</td>');
                                arr.push('<td>' + propetyValueArr[1][j].PropetyValue + '</td>');
                                arr.push('<td><input type="text" class="SkuValueInput2 batch_sallPrice" placeholder="销售价" value="'+_price+'" lay-verify="required|isMoney|greaterThanZero"></td>');
                                arr.push('<td><input type="text" value="'+_stockNum+'" lay-verify="required|number"  class="SkuValueInput2 batch_stockNum" placeholder="库存"></td>');
                                arr.push('<td><input type="text" value="' + _skucode + '" class="SkuValueInput2 batch_skuCode" placeholder="商品编码,非必填"></td>');
                                arr.push('<td><input lay-verify="required" type="text" value="' + _weight + '" class="SkuValueInput2 batch_weight" placeholder="商品重量(kg)"></td>');
                                arr.push('</tr>');
                                _price = ""; _stockNum = ""; _skucode = ""; _weight = "";
                                _cc++;
                            }
                        }
                    }
                    else {
                        var _PropetyCombineId = propetyValueArr[0][i].Id;
                        //计算当前合并属性值ID是否存在已经设置的模型
                        var _model = ProductSkuClass.Instance.GetBindSkuModel(data.MoreSkuModelList, _PropetyCombineId);
                        if (_model != null) {
                            _price = _model.SallPrice;
                            _stockNum = _model.StockNum;
                            _skucode = _model.SkuCode;
                            _weight = _model.Weight;
                        }
                        arr.push('<tr ProppetyCombineName="' + propetyValueArr[0][i].PropetyValue + '" PropetyCombineId="' + _PropetyCombineId + '">');
                        arr.push('<td>' + propetyValueArr[0][i].PropetyValue + '</td>');
                        arr.push('<td><input type="text" value="'+_price+'" class="SkuValueInput2 batch_sallPrice" placeholder="销售价" lay-verify="required|isMoney|greaterThanZero"></td>');
                        arr.push('<td><input type="text" value="'+_stockNum+'" lay-verify="required|number"  class="SkuValueInput2 batch_stockNum" placeholder="库存"></td>');
                        arr.push('<td><input type="text" value="' + _skucode + '" class="SkuValueInput2 batch_skuCode" placeholder="商品编码,非必填"></td>');
                        arr.push('<td><input lay-verify="required" type="text" value="' + _weight + '" class="SkuValueInput2 batch_weight" placeholder="商品重量(kg)"></td>');
                        arr.push('</tr>');
                        _price = ""; _stockNum = ""; _skucode = ""; _weight = "";
                    }
                }
                arr.push('</tbody>');
            }

            return $("#skuTable").html(arr.join(''));
        },
        GetBindSkuModel:function(list,combineId){
            var res = null;
            for (var i = 0; i < list.length; i++) {
                if (list[i].PropetyCombineId == combineId) {
                    res = list[i];
                    break;
                }
            }
            return res;
        },
        ChangeSkuType: function () {
            var val = $(this).val();
            if (val == "1") {
                $("#singleForm").show();
                $("#moreForm").hide();
            } else if (val == "2") {
                $("#moreForm").show();
                $("#singleForm").hide();
            }
        },
        Submit: function () {
            var type = $(this).attr("SkuType");
            if (type == 1) {
                //单规格提交
                ProductSkuClass.Instance.SignleSubmit();
            }
            else if (type == 2) {
                //批量提交
                ProductSkuClass.Instance.MoreSubmit();
            } else if (type == 3) {
                //批量设置
                var SallPrice_batch = $.trim($("#SallPrice_batch").val());
                var StockNum_batch = $.trim($("#StockNum_batch").val());
                var SkuCode_batch = $.trim($("#SkuCode_batch").val());
                var SkuWeight_batch = $.trim($("#SkuWeight_batch").val());
                $(".batch_sallPrice").val(SallPrice_batch);
                $(".batch_stockNum").val(StockNum_batch);
                $(".batch_skuCode").val(SkuCode_batch);
                $(".batch_weight").val(SkuWeight_batch);
            }

        },
        MoreSubmit: function () {
            //如果一行没有直接返回false
            if ($.trim($("#skuTable").html()) == "") {
                return false;
            }
            if (islock)
                return false;
            islock = true;
            var model = {};
            model.ProductId = ToolManager.Common.UrlParms("id");
            model.MoreSkuModelList = [];
            $("#table_body tr").each(function () {
                var sku_model = {};
                sku_model.PropetyCombineId = $(this).attr("PropetyCombineId");
                sku_model.ProppetyCombineName = $(this).attr("ProppetyCombineName");
                sku_model.StockNum = $(this).find(".batch_stockNum").val();
                sku_model.SallPrice = $(this).find(".batch_sallPrice").val();
                sku_model.SkuCode = $(this).find(".batch_skuCode").val();
                sku_model.Weight = $(this).find(".batch_weight").val();
                model.MoreSkuModelList.push(sku_model);
            });
            var index = layer.load(1);
            RequestManager.Ajax.Post("/Product/EditMoreSku", model, true, function (data) {
                layer.close(index);
                islock = false;
                if (data.IsSuccess) {
                    layer.confirm('提交成功,是否返回列表?', {
                        btn: ['确定', '取消'] //按钮
                    }, function () {
                        window.location.href = "/Product/List";
                    }, function () {

                    });

                } else {
                    layer.alert(data.Message);
                }
            })
            
        },
        SignleSubmit: function () {
            if (islock)
                return false;
            islock = true;
            var model = {};
            model.SallPrice = $("#SallPrice").val();
            model.StockNum = $("#StockNum").val();
            model.SkuCode = $("#SkuCode").val();
            model.Weight = $("#SkuWeight").val();
            model.ProductId = ToolManager.Common.UrlParms("id");
            var index = layer.load(1);
            RequestManager.Ajax.Post("/Product/EditSingleSku", model, true, function (data) {
                layer.close(index);
                islock = false;
                if (data.IsSuccess) {
                    layer.confirm('提交成功,是否返回列表?', {
                        btn: ['确定', '取消'] //按钮
                    }, function () {
                        window.location.href = "/Product/List";
                    }, function () {

                    });

                } else {
                    layer.alert(data.Message);
                }
            })
        }

    };
})();